package com.example.demo.service;

import com.example.demo.domain.Question;
import com.example.demo.mapper.QuestionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Optional;

@Service
public class QuestionService implements IQuestionService{

    @Autowired
    private QuestionRepository questionRepository;

    @Override
    public Question getQuestionById(long id)
    {
        return questionRepository.findById(id).orElseThrow(RuntimeException::new);
    }

    @Override
    public Long addNewQuestion(Question question) {
        Optional<Question> questionOptional = questionRepository.findById(question.getQuestionId());

        // 使用 Optional.isPresent() 来判断是否存在该问题
        if (questionOptional.isPresent()) {
            throw new IllegalStateException("questionId: " + question.getQuestionId() + " has been taken");
        }

        // 保存新的 Question
        Question savedQuestion = questionRepository.save(question);

        // 返回保存的 Question 的 ID
        return savedQuestion.getQuestionId();
    }

    @Override
    public List<Question> getQuestionList() {
        return questionRepository.findAll();
    }

}
